<?php

namespace App\Observers;

use App\Models\Health;
use App\servers\RedisService;

class HealthObserver
{
    /**
     * Handle the Health "created" event.
     *
     * @param  \App\Models\Health  $health
     * @return void
     */
    public function created(Health $health)
    {
        $redis = RedisService::getInstance()->getRedis(); //添加数据同步redis
        $redis->select(6);  //选择redis数据库
        $key = 'id:'.$health['id'];  //将 id作为键名存储
        $data = json_encode($health); //转换为JSON字符串
        $redis->set($key,$data);
    }

    /**
     * Handle the Health "updated" event.
     *
     * @param  \App\Models\Health  $health
     * @return void
     */
    public function updated(Health $health)
    {
        // 不能监听数据库查询
        // 观察者只能监听通过面向对象的方式构建查询语句
        $redis = RedisService::getInstance()->getRedis();
        $redis->select(6);
        $data = json_encode($health); // 将 PHP 数组转换为 JSON 字符串
        $redis->set('id:'.$health['id'], $data); // 修改后的 JSON 数据同步到 Redis 中
    }

    /**
     * Handle the Health "deleted" event.
     *
     * @param  \App\Models\Health  $health
     * @return void
     */
    public function deleted(Health $health)
    {
        $redis = RedisService::getInstance()->getRedis();
        $redis->select(6);
        $redis->del('id:'.$health['id']); // 根据键名删除
    }

    /**
     * Handle the Health "restored" event.
     *
     * @param  \App\Models\Health  $health
     * @return void
     */
    public function restored(Health $health)
    {
        //
    }

    /**
     * Handle the Health "force deleted" event.
     *
     * @param  \App\Models\Health  $health
     * @return void
     */
    public function forceDeleted(Health $health)
    {
        //
    }
}
